package com.yylending.las.personal.bandcard;

import android.Manifest;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.tbruyelle.rxpermissions.Permission;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.*;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.VibratorUtil;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.webview.WebViewActivity;
import exocr.bankcard.BankManager;
import exocr.bankcard.DataCallBack;
import exocr.bankcard.EXBankCardInfo;
import exocr.bankcard.ViewEvent;
import exocr.engine.EngineManager;
import ocr.bankcard.BankCardScanView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HenryZhang on 2016/11/10.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 * <p>
 * 开户行输入or选择
 */
public class AddCardFragment extends BaseFragment implements BankCardPresenter.View, CardBinPresenter.View, View.OnClickListener,
        DataCallBack, ViewEvent, BankCardScanView.OnBackListener, View.OnFocusChangeListener {
    private final static String TAG = AddCardFragment.class.getSimpleName();
    EXBankCardInfo mEXBankCardInfo;
    private View mParentLl;
    private TextView mCardOwnerTx;
    private TextView mCardNameTx;
    private EditText mCardNumberTx;
    //private EditText mPhoneNum;
    private TextView mSupportBankTv;
    private View mCustomerView;
    private BankCardScanView mCustomView;
    //滚轮蒙板
    private View mMasker;
    private BankCardPresenter mBankCardPresenter;
    private CardBinPresenter mCardBinPresenter;
    //是否正在扫描操作
    private boolean mOperating = false;
    private List<BankCardModel.SupportBankList.SupportBank> mSupportBankList = new ArrayList<>();
    private CardBinModel.CardBin mCardBin;
    private String mOriginFrom = "";
    private String mPreviewBankCardNum = "";
    private boolean mRequestCardBinSuccess = false;
    private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
        @Override
        public void permissionsEachGrantedResult(Permission permission) {
            switch (permission.name) {
                case Manifest.permission.CAMERA:
                    if (permission.granted) {
                        mOperating = true;
                        scanCard();
                    } else {
                        mOperating = false;
                        showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void PermissionsAllGrantedResult(boolean granted, int requestCode) {}
    };

    public static BaseFragment newInstance(String originFrom) {
        BaseFragment fragment = new AddCardFragment();
        Bundle args = new Bundle();
        args.putString(BankCardActivity.KEY_INTENT_ORIGIN_FROM_TO_BIND_CARD, originFrom);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_bank_card, null);

        mParentLl = view.findViewById(R.id.parent_ll);
        // 默认获取焦点并关闭软键盘.
        rootViewFocus();
        // 点击空白处获取焦点并关闭软键盘.
        mParentLl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    rootViewFocus();
                }
                return false;
            }
        });

        View bankCardOwnerRl = view.findViewById(R.id.bank_card_owner_rl);
        bankCardOwnerRl.setOnClickListener(this);
        View capture = view.findViewById(R.id.add_band_card_capture);
        capture.setOnClickListener(this);
        View cardName = view.findViewById(R.id.add_band_card_name_container);
        cardName.setOnClickListener(this);
        View bind = view.findViewById(R.id.add_bank_card_bind);
        bind.setOnClickListener(this);

        mCardOwnerTx = (TextView) view.findViewById(R.id.add_band_card_owner);
        mCardNameTx = (TextView) view.findViewById(R.id.add_band_card_name);
        mCardNumberTx = (EditText) view.findViewById(R.id.add_band_card_number);
        //mPhoneNum = (EditText) view.findViewById(R.id.phone_number_edt);
        mMasker = view.findViewById(R.id.add_bank_card_wheel_view_masker);
        mSupportBankTv = (TextView) view.findViewById(R.id.support_bank_tv);
        mSupportBankTv.setOnClickListener(this);
        mCardNumberTx.setOnFocusChangeListener(this);

        if (!TextUtils.isEmpty(Global.LOGIN_REAL_NAME)) {
            mCardOwnerTx.setText(Global.LOGIN_REAL_NAME);
        }

        mCustomerView = inflater.inflate(R.layout.bank_card_scan_custom_view, null);
        mCustomView = (BankCardScanView) mCustomerView.findViewById(R.id.custom_id);
        mCustomView.setListener(this);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        BankManager.getInstance().setRecoSupportOrientation(BankManager.supportOrientations.onlyLandscapeLeft);
        BankManager.getInstance().setView(mCustomerView);
        getActivity().getSupportLoaderManager().initLoader(BankCardActivity.LOADER_ID_BIND_CARD, null, this);
        getActivity().getSupportLoaderManager().initLoader(BankCardActivity.LOADER_ID_GET_CARD_BIN, null, this);

        mOriginFrom = getArguments().getString(BankCardActivity.KEY_INTENT_ORIGIN_FROM_TO_BIND_CARD, "");
    }

    @Override
    public Loader<Presenter> onCreateLoader(int id, Bundle args) {
        switch (id) {
            case BankCardActivity.LOADER_ID_BIND_CARD:
                return new PresenterLoader<>(getActivity(), new BankCardPresenter.Generator());
            case BankCardActivity.LOADER_ID_GET_CARD_BIN:
                return new PresenterLoader<>(getActivity(), new CardBinPresenter.Generator());
            default:
                break;
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
        switch (loader.getId()) {
            case BankCardActivity.LOADER_ID_BIND_CARD:
                mBankCardPresenter = (BankCardPresenter) data;
                mBankCardPresenter.attach(this);
//				mBankCardPresenter.getSupportBankList();
                break;
            case BankCardActivity.LOADER_ID_GET_CARD_BIN:
                mCardBinPresenter = (CardBinPresenter) data;
                mCardBinPresenter.attach(this);
                break;
            default:
                break;
        }
    }

	@Override
	public void onResume() {
		super.onResume();
		CLog.i(TAG, "onResume()--");
		mOperating = false;
	}

	@Override
    public void onStart() {
        super.onStart();
		CLog.i(TAG, "onStart()--");
		Global.setThirdPartyPageOpenedFlag(false);
    }

    private void rootViewFocus() {
        mParentLl.setFocusable(true);
        mParentLl.setFocusableInTouchMode(true);
        mParentLl.requestFocus();
        YJKD.hideInputWindow(getActivity());
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.add_band_card_number:
                if (!hasFocus && getActivity() != null && !getActivity().isFinishing()) {
                    String cardNum = mCardNumberTx.getText().toString();
                    needRequestCardBin(cardNum, CardBinPresenter.FUNCTION_CODE_CARD_BIN_FROM_OTHERS);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_band_card_name_container:
            case R.id.bank_card_owner_rl:
                rootViewFocus();
                break;
            case R.id.add_bank_card_bind:
                doBindCardAction(CardBinPresenter.FUNCTION_CODE_CARD_BIN_FROM_BIND_CARD_BTN_CLICKED);
                break;
            case R.id.add_band_card_capture:
                YJKD.hideInputWindow(getActivity());
                if (!mOperating) {
                    if (PermissionsGrantedHelper.isSdkUnderM()) {
                        // TODO: 2017/6/15 这个判断只在魅族手机上有效?
                        if (PermissionsGrantedHelper.checkCameraPermission()) {
                            mOperating = true;
                            scanCard();
                        } else {
                            mOperating = false;
                            showNeedPermission(getString(R.string.camera_permission_hint, getString(R.string.app_name)));
                        }
                    } else {
                        PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.CAMERA);
                    }
                }
                break;
            case R.id.support_bank_tv:
				StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CHECK_BANK_LIST);
				WebViewActivity.start(getActivity(), Global.BASE_URL + Global.SUPPORT_BANK_LIST_URL, getString(R.string.support_bank_list), "");
                break;
            default:
                break;
        }
    }

    private void doBindCardAction(int functionCode) {
        if (TextUtils.isEmpty(mCardNumberTx.getText().toString())) {
            showToast(R.string.input_correct_account);
            return;
        } else if (needRequestCardBin(mCardNumberTx.getText().toString(), functionCode)) {
            return;
        }
        /*if (TextUtils.isEmpty(mPhoneNum.getText().toString()) || !RegexUtil.isMobileNumber(mPhoneNum.getText().toString())) {
            showToast(R.string.check_phone_num);
            return;
        }*/

        if (mCardBin != null){
            mBankCardPresenter.bindBankCard(Global.LOGIN_REAL_NAME, mCardBin.bankNo, mCardNumberTx.getText().toString(), "");//mPhoneNum.getText().toString());
        }
    }

    @Override
    public void bindCardSuccess() {
        showToast(R.string.bind_card_success);
        if (TextUtils.equals(Constants.KEY_GOTO_BIND_CARD_FROM_HAVE_QUOTA_FRAGMENT, mOriginFrom)) {
            ArrayList<BoundBankCards.BankInfo> bankInfoArrayList = new ArrayList<>();
            BoundBankCards.BankInfo bankInfo = new BoundBankCards.BankInfo();
            bankInfo.setBankName(mCardNameTx.getText().toString());
            bankInfo.setNumber(mCardNumberTx.getText().toString());
            bankInfoArrayList.add(bankInfo);
            MyQuotaModel.ApplyStatus applyStatus = getActivity().getIntent().getParcelableExtra(BankCardActivity.KEY_INTENT_APPLY_STATUS);

            if (applyStatus != null) {
                ProcessActivity.start(getActivity(), applyStatus, bankInfoArrayList);
            }
        }
        getActivity().finish();
    }

    @Override
    public void bindCardFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void hasBindBankCard(boolean isManual, List<BoundBankCards.BankInfo> bankInfo) {

    }

    @Override
    public void neverBindBankCard(boolean isManual) {

    }

    @Override
    public void requestBindBankCardFailed(boolean isManual) {

    }

    @Override
    public void getSupportBankSuccess(List<BankCardModel.SupportBankList.SupportBank> supportBankList) {
        mSupportBankList.addAll(supportBankList);
    }

    @Override
    public void getSupportBankFailed(String msg) {

    }

	@Override
	public void bindCardRetCode(String retCode) {
		StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_0CARDS,retCode);

	}

	@Override
    public void getCardBinSuccess(CardBinModel.CardBin cardBin, int functionCode) {
        mRequestCardBinSuccess = true;
        // 如果是点击绑定按钮拉取卡bin信息, 则获取成功后需调用绑卡接口.
        if (functionCode == CardBinPresenter.FUNCTION_CODE_CARD_BIN_FROM_BIND_CARD_BTN_CLICKED) {
            doBindCardAction(functionCode);
        }

        // 保存本地请求的卡号
        mPreviewBankCardNum = mCardNumberTx.getText().toString();
        mCardBin = cardBin;
        mCardNameTx.setText(cardBin.bankName);
        mCardNameTx.setTextColor(getResources().getColor(R.color.color_333333));
    }

    @Override
    public void getCardBinFailed(String msg) {
        mRequestCardBinSuccess = false;
        // 保存本地请求的卡号
        mPreviewBankCardNum = mCardNumberTx.getText().toString();
        mCardNameTx.setText(msg);
        mCardNameTx.setTextColor(getResources().getColor(R.color.color_ff4c29));
    }

    @Override
    public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
        super.onFunctionalError(e, autoTips, functionalCode);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRequestCardBinSuccess = false;
                // 保存本地请求的卡号
                mPreviewBankCardNum = mCardNumberTx.getText().toString();
            }
        });
    }

    private void scanCard() {
        //忽略手势密码
        Global.setThirdPartyPageOpenedFlag(true);
        BankManager.getInstance().recognize(this, getActivity());
    }

    private boolean needRequestCardBin(String cardNum, int functionCode) {
        boolean needRequestCardBin = false;
        // 这里比对一下前一次发请求获取卡bin的银行卡号是否和本次的一样, 如果一样, 则不发请求;
        // 这里同时也是为了解决如果用户手动输入银行卡号, 然后点击绑定按钮时, 需先判断一下是否获取成功了卡bin信息.
        if (!mRequestCardBinSuccess || !TextUtils.equals(mPreviewBankCardNum, cardNum)) {
            needRequestCardBin = true;
            mCardBinPresenter.getCardBin(cardNum, functionCode);
        }
        return needRequestCardBin;
    }

    @Override
    public void onBankCardDetected(boolean success) {
        mEXBankCardInfo = null;
        mOperating = false;
        if (success) {
            VibratorUtil.vibrate(getActivity(), 100);
            mEXBankCardInfo = BankManager.getInstance().getCardInfo();
            BankManager.getInstance().stopRecognize();
            if (mEXBankCardInfo != null && !TextUtils.isEmpty(mEXBankCardInfo.strNumbers)) {
                mCardNameTx.setTextColor(getResources().getColor(R.color.color_333333));
                mCardNumberTx.setText(mEXBankCardInfo.strNumbers);
                mCardNumberTx.setSelection(mEXBankCardInfo.strNumbers.length());
                needRequestCardBin(mEXBankCardInfo.strNumbers, CardBinPresenter.FUNCTION_CODE_CARD_BIN_FROM_OTHERS);
            }
        } else {
            showToast(R.string.cannot_identify_bank_card);
        }
    }

    @Override
    public void onCameraDenied() {
        mOperating = false;
    }

    /**
     * 显示权限被禁用提示框
     */
	private void showNeedPermission(String tips){
		showTwoBtnDialog(tips, getString(R.string.go_to_settings), getString(R.string.cancel), new CommonDialog.ButtonClickListener() {
			@Override
			public void onCancel(CommonDialog dialog) {
				dialog.dismiss();
			}

			@Override
			public void onConfirm(CommonDialog dialog) {
				//忽略手势密码
				Global.setThirdPartyPageOpenedFlag(true);
				Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
				startActivity(intent);
				dialog.dismiss();
			}
		}, true);
	}

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EngineManager.getInstance().finishEngine();
        getActivity().getSupportLoaderManager().destroyLoader(BankCardActivity.LOADER_ID_BIND_CARD);
        getActivity().getSupportLoaderManager().destroyLoader(BankCardActivity.LOADER_ID_GET_CARD_BIN);
    }

    @Override
    public Rect getRectByOrientation(int i) {
        return mCustomView.getGuide();
    }

    @Override
    public void invalideView(int i) {

    }

    @Override
    public void goBack() {
        mOperating = false;
        BankManager.getInstance().stopRecognize();
    }

    @Override
    public void onLightChanged(float v) {

    }

    public void clearText() {
		mRequestCardBinSuccess = false;
		mPreviewBankCardNum = "";
        if (mCardNameTx != null) {
            mCardNameTx.setText("");
        }
        if (mCardNumberTx != null) {
            mCardNumberTx.setText("");
        }
        /*if (mPhoneNum != null) {
            mPhoneNum.setText("");
        }*/
    }

	public boolean giveUpBind() {
		if(!TextUtils.isEmpty(mCardNumberTx.getText().toString().trim())){
			return true;
		}
		if(!TextUtils.isEmpty(mCardNameTx.getText().toString().trim())){
			return true;
		}
		/*if(!TextUtils.isEmpty(mPhoneNum.getText().toString().trim())){
			return true;
		}*/
		return false;
	}
}